package co.za.itweb.securedata;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Toast;

public class Refresh extends Activity {
	RefreshTask rt;
	ArrayList<String> feedList = new ArrayList<String>(0);
	InputStream is = null;
	String result = "";
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		
		if (internetConnection()) {

			rt = new RefreshTask(this);
			
		
				rt.execute();
			

		} else {
			Toast.makeText(getApplicationContext(),
					"No Internet connection ...", Toast.LENGTH_LONG).show();
			Refresh.this.finish();
		}

	}

	public boolean internetConnection() {
		ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = connMgr.getActiveNetworkInfo();

		return (info != null && info.isConnected());

	}

	@Override
	public void onPause() {
		super.onPause();
		if (rt.getStatus() == AsyncTask.Status.RUNNING) {
			rt.dialog.dismiss();
			rt.cancel(true);
			

		}

	}

	

	private class RefreshTask extends AsyncTask<Void, Integer, Void> {
		ArrayList<RSSFeed> fList2 = new ArrayList<RSSFeed>(0);
		RSSFeed feed;
		ProgressDialog dialog;
		

		public RefreshTask(Refresh activity) {
			
			dialog = new ProgressDialog(activity);
			
			dialog.setMessage("Refreshing...");
			
			dialog.setCancelable(true);
			dialog.setOnCancelListener(new DialogInterface.OnCancelListener(){
		          public void onCancel(DialogInterface dialog) {
		              rt.cancel(true);
		              Intent returnIntent = new Intent();
		  			setResult(RESULT_CANCELED, returnIntent);
		              Refresh.this.finish();
		          }
		    });
		}

		protected void onPreExecute() {
			
			fList2.clear();
			
			dialog.show();
			
		}

		@Override
		protected Void doInBackground(Void... params) {

			 
					try {
//						if(!First.jArray.getString("latestnews").isEmpty()){
						        feed = getFeed("http://itweb.mobi/_feed/vpo/_load.php/?device_os=android&company_folder=securedata&sections=latest_news&parse_type=full&load_type=full&print_type=xml");
						        if (feed != null) {
						        	fList2.add(feed);
								    }
//						}
//						if(!First.jArray.getString("sectornews").isEmpty()){	
								feed = getFeed("http://itweb.mobi/_feed/vpo/_load.php/?device_os=android&company_folder=securedata&sections=sector_news&parse_type=full&load_type=full&print_type=xml");	
								if (feed != null) {
									fList2.add(feed);
								    }
//						}
							 
						if (isCancelled()) {
							System.out.println("CANCELLEEEEDDDDDDDDDDDDDDDDDDD");
							fList2.clear();
							
							
							
							
							Intent returnIntent = new Intent();
							returnIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
							setResult(RESULT_CANCELED,returnIntent);

							finish();

							
							return null;
						}

						
						
					} catch (Exception e) {

						e.printStackTrace();
						return null;
					}

					
					


					return null;
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			dialog.setProgress(values[0]);

		}

		@Override
		protected void onPostExecute(Void result) {
			if (dialog.isShowing()) {
				
				First.List.clear();
				First.List=fList2;
				Intent returnIntent = new Intent();
				setResult(RESULT_OK, returnIntent);
				dialog.dismiss();
				finish();
			}
			

		}
	}
	
	
	public boolean parseConfig() {
		try {

			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(First.url);

			JSONObject obj = new JSONObject();
			obj.put("conf", "conf");
			httppost.setEntity(new StringEntity(obj.toString(), "UTF-8"));

			httppost.setHeader("Accept", "application/json");
			httppost.setHeader("Content-type", "application/json");

			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();

		} catch (Exception e) {
			Log.e("log_tag", "Error in http connection " + e.toString());
		}

		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "iso-8859-1"), 8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");

			}
			is.close();
			result = sb.toString();
		} catch (Exception e) {
			Log.e("log_tag", "Error converting result " + e.toString());
		}

		// try parse the string to a JSON object
		try {
			First.jArray = new JSONObject(result);
			
			
			return true;

		} catch (JSONException e) {
			Log.e("log_tag", "Error parsing data " + e.toString());
		}

		return false;

		
	}
	

	public RSSFeed getFeed(String urlToRssFeed) {
		try {

			URL url = new URL(urlToRssFeed);

			SAXParserFactory factory = SAXParserFactory.newInstance();
			factory.setNamespaceAware(true);

			SAXParser parser = factory.newSAXParser();

			XMLReader xmlreader = parser.getXMLReader();

			RSSHandler theRssHandler = new RSSHandler();

			xmlreader.setContentHandler(theRssHandler);

			InputSource is = new InputSource(url.openStream());

			xmlreader.parse(is);

			System.out.println("FFFFFFFEEEEEEEEEEEDDDDDDDDDDDDDDDDD"
					+ theRssHandler.getFeed());
			return theRssHandler.getFeed();
		} catch (Exception ee) {
			System.out.println("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
					+ ee.toString());
			return null;
		}
	}
	
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
	    if ((keyCode == KeyEvent.KEYCODE_BACK))
	    {
	    	System.out.println("BBBBBBBBBBBAAAAAAAAAAAAACCCCCCCCCCCCCCKKKKKKKKKKKKKKKKKKKKKKKKKKKKK");
	    	if(rt.dialog.isShowing()){
	    	rt.dialog.dismiss();
	    	rt.cancel(true);
	    	
	    	Intent returnIntent = new Intent();
			setResult(RESULT_CANCELED, returnIntent);
			Refresh.this.finish();
	    	}
	    	
	    	 return true;
	    }
	    return super.onKeyDown(keyCode, event);
	}
	
	

}